package com.mysql.test;

import com.mysql.entity.Student;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sunpeng
 * @Date 2021-07-02 11:05
 */

//基础
public class Base {

    @Test
    public void add() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        //url, name, password, database, 参数
        String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=utf-8";
        Connection connection = DriverManager.getConnection(url, "root", "610527");

        String sql = "insert into student values(105, 'sunpeng', 80, 20) ";
        Statement statement = connection.createStatement();
        int i = statement.executeUpdate(sql);
        System.out.println(i);

        statement.close();
        connection.close();
    }

    @Test
    public void query() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=utf-8";
        Connection connection = DriverManager.getConnection(url, "root", "610527");

        Statement statement = connection.createStatement();
        String sql = "select * from student ";
        ResultSet resultSet = statement.executeQuery(sql);

        List<Student> students = new ArrayList<>();
        while (resultSet.next()){
            Student student = new Student();
            student.setId(resultSet.getLong("id"));
            student.setName(resultSet.getString("name"));
            student.setScore(resultSet.getDouble("score"));
            student.setAge(resultSet.getInt("age"));
            students.add(student);
        }
        System.out.println(students);
    }

}
